<?php

namespace app\api\controller\v1;
include_once APP_PATH . 'api/common.php';
use app\common\controller\Api;
use think\Db;
use think\Request;
use think\Validate;

class Leave extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    private function ensureTables()
    {
        $t1 = Db::query("SHOW TABLES LIKE 'fa_leave'");
        if (!$t1) {
            $sql = "CREATE TABLE `fa_leave` (
              `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
              `user_id` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '申请人ID[index,key]',
              `class_id` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '班级ID[key]',
              `class_type` int(10) unsigned NOT NULL DEFAULT 1 COMMENT '班级类型[select,content:1=学校班级|2=社区班级]',
              `reason` text COMMENT '请假原因[type:text]',
              `start_time` datetime DEFAULT NULL COMMENT '开始时间[type:datetime]',
              `end_time` datetime DEFAULT NULL COMMENT '结束时间[type:datetime]',
              `approval_status` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '审批状态[select,content:0=待审|1=通过|2=拒绝]',
              `approval_comment` text COMMENT '审批意见[type:text]',
              `create_time` datetime DEFAULT NULL COMMENT '创建时间[type:datetime]',
              `update_time` datetime DEFAULT NULL COMMENT '更新时间[type:datetime]',
              `delete_time` datetime DEFAULT NULL COMMENT '删除时间[type:datetime,hidden]',
              `status` int(11) NOT NULL DEFAULT 1 COMMENT '状态[select,content:0=关闭|1=开启]',
              `weigh` int(11) NOT NULL DEFAULT 0 COMMENT '权重',
              PRIMARY KEY (`id`),
              KEY `user_id` (`user_id`),
              KEY `class_id` (`class_id`),
              KEY `weigh_id` (`weigh`,`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='请假记录'";
            Db::execute($sql);
        }
    }

    public function apply(Request $request)
    {
        $this->ensureTables();
        $user = $this->auth->getUser();
        if (!$user || !isset($user['uid'])) {
            return json(['code' => 0, 'msg' => '未登录', 'data' => null]);
        }
        file_put_contents($_SERVER["DOCUMENT_ROOT"]."/../"."log_leave.txt", date('Y-m-d H:i:s')." apply uid=".$user['uid']."\n", FILE_APPEND);

        $data = $request->post();
        $data['user_id'] = $user['uid'];
        $validate = new Validate();
        $validate->rule([
            'class_id' => 'require|number',
            'class_type' => 'require|in:1,2',
            'reason' => 'require|max:5000',
            'start_time' => 'require|date',
            'end_time' => 'require|date'
        ]);
        if (!$validate->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }
        if (strtotime($data['end_time']) < strtotime($data['start_time'])) {
            return json(['code' => 0, 'msg' => '结束时间需大于开始时间']);
        }
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['update_time'] = $data['create_time'];
        $data['status'] = 1;
        $data['weigh'] = 0;
        $data['approval_status'] = 0;
        $id = Db::name('fa_leave')->insertGetId($data);
        return json(['code' => 200, 'msg' => '提交成功', 'data' => ['id' => $id]]);
    }

    public function lists(Request $request)
    {
        $this->ensureTables();
        $user = $this->auth->getUser();
        if (!$user || !isset($user['uid'])) {
            return json(['code' => 0, 'msg' => '未登录', 'data' => null]);
        }
        $year = intval($request->get('year', 0));
        $month = intval($request->get('month', 0));
        $class_id = intval($request->get('class_id', 0));
        $class_type = intval($request->get('class_type', 0));
        $q = Db::name('fa_leave')->where('user_id', $user['uid'])->where('status', 1);
        if ($class_id > 0) $q->where('class_id', $class_id);
        if ($class_type > 0) $q->where('class_type', $class_type);
        if ($year > 0 && $month > 0) {
            $start = sprintf('%04d-%02d-01 00:00:00', $year, $month);
            $end = date('Y-m-t 23:59:59', strtotime($start));
            $q->where('start_time', '>=', $start)->where('start_time', '<=', $end);
        }
        $list = $q->order('start_time desc')->limit(100)->select();
        return json(['code' => 200, 'msg' => 'ok', 'data' => $list]);
    }
}